from sqlalchemy import Column, Integer, String, JSON, DateTime, func, Boolean, Text
from sqlalchemy.orm import relationship
from core.base.orm_model import Base, TimestampMixin
from datetime import datetime


class SysDataPermissionRule(Base, TimestampMixin):
    """数据权限规则模型"""
    __tablename__ = "sys_data_permission_rule"
    
    id = Column(Integer, primary_key=True, index=True, comment='数据权限规则ID')
    name = Column(String(64), unique=True, nullable=False, index=True, comment='规则名称')
    rule_code = Column(String(50), unique=True, index=True, comment='规则编码')
    table_name = Column(String(64), nullable=False, comment='目标表名')
    logical_operator = Column(String(10), nullable=False, default='OR', comment='多条件组合方式: AND/OR')
    condition_type = Column(String(20), nullable=False, comment='条件类型：eq,in,like,between等')
    config_json = Column(JSON, nullable=False, comment='权限配置JSON')
    description = Column(Text, nullable=True, comment='规则描述')
    status = Column(Boolean, nullable=False, default=True, comment='是否启用')
    create_time = Column(DateTime, default=datetime.now, comment="创建时间")
    update_time = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment="更新时间")
    
    def __repr__(self):
        return f"<SysDataPermissionRule {self.name}>"


class SysRoleDataPermission(Base, TimestampMixin):
    """角色数据权限关联模型"""
    __tablename__ = "sys_role_data_permission"
    
    id = Column(Integer, primary_key=True, index=True, comment='关联ID')
    role_id = Column(Integer, nullable=False, index=True, comment='角色ID')
    rule_id = Column(Integer, nullable=False, index=True, comment='数据权限规则ID')
    status = Column(Boolean, nullable=False, default=True, comment='是否启用')
    create_time = Column(DateTime, default=datetime.now, comment="创建时间")
    update_time = Column(DateTime, default=datetime.now, onupdate=datetime.now, comment="更新时间")
    
    def __repr__(self):
        return f"<SysRoleDataPermission role_id={self.role_id} rule_id={self.rule_id}>"